const { StudentProgress, User, Course } = require('../models');
const { Op } = require('sequelize');

// 获取所有学生进度
exports.getAllProgress = async (req, res) => {
  try {
    const progress = await StudentProgress.findAll({
      include: [User, Course]
    });
    res.json(progress);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching progress', error });
  }
};

// 获取聚合的学生进度数据（用于管理页面）
exports.getAggregatedProgress = async (req, res) => {
  try {
    // 获取所有学生用户
    const students = await User.findAll({
      where: { role: 'student' }
    });

    const aggregatedData = [];

    for (const student of students) {
      // 获取该学生的所有学习记录
      const progressRecords = await StudentProgress.findAll({
        where: { userId: student.id },
        order: [['timestamp', 'DESC']]
      });

      // 计算章节进度
      const chapters = [];
      const totalChapters = 5; // 假设有5个章节
      
      for (let i = 1; i <= totalChapters; i++) {
        const chapterRecords = progressRecords.filter(record => record.chapterId === i);
        const videoProgress = chapterRecords.length > 0 ? 100 : 0; // 简化计算，有记录就是100%
        const exerciseProgress = chapterRecords.length > 0 ? 100 : 0;
        const lastActivity = chapterRecords.length > 0 ? chapterRecords[0].timestamp : null;
        
        chapters.push({
          chapter: i,
          videoProgress,
          exerciseProgress,
          materialProgress: chapterRecords.length > 0 ? 100 : 0, // 简化计算，有记录就是100%
          lastActivity
        });
      }

      // 计算总进度
      const completedChapters = chapters.filter(ch => ch.videoProgress > 0).length;
      const totalProgress = Math.round((completedChapters / totalChapters) * 100);

      // 获取最近活动（最多5条）
      const recentActivities = progressRecords.slice(0, 5).map(record => ({
        id: record.id,
        actionType: record.actionType,
        chapter: record.chapterId,
        timestamp: record.timestamp,
        createdAt: record.createdAt || record.timestamp
      }));

      aggregatedData.push({
        id: student.id,
        name: student.username,
        email: student.email,
        totalProgress,
        chapters,
        recentActivities
      });
    }

    res.json(aggregatedData);
  } catch (error) {
    console.error('Error fetching aggregated progress:', error);
    res.status(500).json({ message: 'Error fetching aggregated progress', error: error.message });
  }
};

// 根据用户ID获取进度
exports.getProgressByUserId = async (req, res) => {
  try {
    const { userId } = req.params;
    const progress = await StudentProgress.findAll({
      where: { userId },
      include: [Course]
    });
    if (!progress) {
      return res.status(404).json({ message: 'Progress not found for this user' });
    }
    res.json(progress);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching progress', error });
  }
};

// 获取当前用户的学习进度
exports.getCurrentUserProgress = async (req, res) => {
  try {
    const userId = req.user?.id;
    
    if (!userId) {
      return res.status(401).json({ error: '用户未认证' });
    }
    
    const progress = await StudentProgress.findAll({
      where: { userId },
      order: [['timestamp', 'DESC']]
    });
    
    res.json(progress);
  } catch (error) {
    console.error('获取当前用户学习进度失败:', error);
    res.status(500).json({ error: '获取学习进度失败' });
  }
};

// 创建或更新进度
exports.createOrUpdateProgress = async (req, res) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({ error: '用户未认证' });
    }

    const { courseId, chapterId, lessonId, actionType, details } = req.body;

    if (!actionType) {
        return res.status(400).json({ error: 'actionType is required' });
    }

    const progress = await StudentProgress.create({
      userId,
      courseId,
      chapterId,
      lessonId,
      actionType,
      details
    });

    res.status(201).json(progress);
  } catch (error) {
    console.error('Error creating progress record:', error);
    res.status(500).json({ message: 'Error creating or updating progress', error: error.message });
  }
};